<?php

namespace app\common\controller;

use app\common\model\User;
use app\common\model\UserToken;
use think\Controller;
use app\common\lib\redis\Redis;
use app\common\lib\Util;
use think\facade\Log;

class Base extends Controller
{
    protected $token = '';
    public $userId = 0;
    public $accid = 0;

    public function __construct()
    {
        parent::__construct();
        $this->cors();
        $url = request()->url();
        if ($url != '/netease/save') {
            $this->token = request()->token;
            $tokenStatus = $this->checkToken($this->token);
            if ($tokenStatus['code'] != 200) {
                Util::apiResponse([], $tokenStatus['msg'], $tokenStatus['code']);
                exit;
            }
            $this->userId = $tokenStatus['user_id'];
            $this->accid = $tokenStatus['accid'];
        }
    }

    //跨域
    public function cors()
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }


    //验证token有效性
    public function checkToken($token)
    {
        if (empty($token) && $token != '0') {
            return ['msg' => '无token', 'code' => 401];
        }
        $tokenExist = UserToken::field('id,user_id,token')
            ->with(['user' => function ($query) {
                $query->field('id,accid');
            }])->where(['token' => $token])
            ->whereTime('token_expire_time', '>', time())->find();
        if (!$tokenExist['user']) {
            return ['msg' => '用户不存在', 'code' => 401];
        }
        return ['user_id' => $tokenExist['user_id'], 'accid' => $tokenExist['user']['accid'], 'msg' => '', 'code' => 200];
    }

    /**
     * @param $apiName 名称
     * @param $limit 限制访问次数
     * @param $time  时间段内
     */
    public static function apiLimit($name, $limit = 3, $time = 60)
    {
        $redis = Redis::getInstance();
        $exist = $redis->exists($name);
        //时间段内已经请求过
        if ($exist) {
            $redis->incr($name);
            $count = $redis->get($name);
            if ($count > $limit) {
                return ['msg' => '请求次数过多，请稍后重试', 'code' => 429];
            }
        } else {
            $redis->incr($name);
            $redis->expire($name, $time);
        }
        $count = $redis->get($name);
        return ['msg' => '你请求了' . $count . '次请求', 'code' => 200];
    }
}
